package com.yilee.idouban;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.yilee.idouban.authorize.WebViewActivity;
import com.yilee.idouban.db.DbHelper;
import com.yilee.idouban.task.GetUserInfoTask;
import com.yilee.idouban.task.common.GenericTask;
import com.yilee.idouban.task.common.TaskAdapter;
import com.yilee.idouban.task.common.TaskListener;
import com.yilee.idouban.task.common.TaskParams;
import com.yilee.idouban.task.common.TaskResult;

public class MainActivity extends OrmLiteBaseActivity<DbHelper> {

	private Button bt_start_authorize;
	private GetUserInfoTask getUserInfoTask;

	private void initComponents() {
		bt_start_authorize = (Button) findViewById(R.id.bt_start_authorize);
		bt_start_authorize.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				String douban_url = (String) getResources().getString(
						R.string.douban_url);
				String api_key = (String) getResources().getString(
						R.string.api_key);
				String redirect_uri = (String) getResources().getString(
						R.string.redirect_uri);
				String auth_url = douban_url + "?" + "client_id=" + api_key
						+ "&redirect_uri=" + redirect_uri
						+ "&response_type=token";

				Intent intent = new Intent(MainActivity.this,
						WebViewActivity.class);
				Bundle b = new Bundle();
				b.putString("url", auth_url);
				intent.putExtras(b);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initComponents();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Bundle b = intent.getExtras();
		if (b != null && b.containsKey("result")) {
			String result = b.getString("result");
			if (result.equals("0")) {
				Toast.makeText(MainActivity.this,
						"授权失败：" + b.getString("error"), Toast.LENGTH_SHORT)
						.show();
			} else {
				// 1. access_token存入数据库
				// TODO
				// 2. 获取用户信息
				/*
				 * GetUserInfoTask task = new
				 * GetUserInfoTask(MainActivity.this);
				 * task.execute("https://api.douban.com/people/@me",
				 * b.getString("access_token"));
				 */
				getUserInfo("https://api.douban.com/people/@me",
						b.getString("access_token"));
			}
		}

	}

	/*
	 * private class GetUserInfoTask extends AsyncTask<String, Integer,
	 * Hashtable<String, Object>> {
	 * 
	 * private ProgressDialog pdialog; private Context context;
	 * 
	 * public GetUserInfoTask(Context context) { this.context = context; }
	 * 
	 * @Override protected void onPreExecute() { pdialog = new
	 * ProgressDialog(context, 0); pdialog.setMessage("正在更新个人信息");
	 * pdialog.show(); super.onPreExecute(); }
	 * 
	 * @Override protected Hashtable<String, Object> doInBackground(String...
	 * arg0) { Hashtable<String, Object> ht = new Hashtable<String, Object>();
	 * String url = arg0[0]; String access_token = arg0[1]; Map<String, String>
	 * map = new HashMap<String, String>(); map.put("Authorization", "Bearer " +
	 * access_token); try { HttpURLConnection conn =
	 * HttpRequestUtil.sendGetRequest(url, null, map); conn.connect(); Person p
	 * = SAXPraserService.getPersonFromXML(conn .getInputStream());
	 * conn.disconnect(); ht.put("result", "1"); ht.put("person", p); } catch
	 * (Exception e) { ht.put("result", "0"); ht.put("message", e.getMessage());
	 * } return ht; }
	 * 
	 * @Override protected void onPostExecute(Hashtable<String, Object> ht) { if
	 * (ht.get("result").toString().equals("0")) {
	 * Toast.makeText(MainActivity.this, "获取信息异常:" + ht.get("message"),
	 * Toast.LENGTH_SHORT) .show(); } else { // TODO // 1. 开始存入数据库 try {
	 * Dao<Person, Integer> personDao = getHelper().getPersonDao();
	 * personDao.create((Person) ht.get("person")); } catch (Exception e) {
	 * Toast.makeText(MainActivity.this, "创建数据库异常:" + e.getMessage(),
	 * Toast.LENGTH_SHORT) .show(); } // 2. 更新首页 } pdialog.dismiss();
	 * super.onPostExecute(ht); }
	 * 
	 * }
	 */

	private void getUserInfo(String url, String access_token) {
		if (getUserInfoTask != null
				&& getUserInfoTask.getStatus() == GetUserInfoTask.Status.RUNNING) {
			return;
		} else {
			getUserInfoTask = new GetUserInfoTask();
			getUserInfoTask.setListener(getUserInfoTaskListener);
			TaskParams params = new TaskParams();
			params.put("url", url);
			params.put("access_token", access_token);
			getUserInfoTask.execute(params);
		}
	}

	private TaskListener getUserInfoTaskListener = new TaskAdapter() {

		@Override
		public String getName() {
			return "getUserInfoTask";
		}

		@Override
		public void onPostExecute(GenericTask task, TaskResult result) {
			if (result == TaskResult.OK) {
				Toast.makeText(MainActivity.this, "成功"+getUserInfoTask.p.getLocation(), Toast.LENGTH_SHORT)
						.show();
			} else if (result == TaskResult.IO_ERROR) {
				Toast.makeText(MainActivity.this, "网络错误", Toast.LENGTH_SHORT)
						.show();
			}
			super.onPostExecute(task, result);
		}

	};
}
